/*
 * exception.c
 *
 * Copyright (C) 2017 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <common.h>
#include <exception.h>
#include <syscalls.h>
#include <process.h>
#include <video.h>
#include <vm86.h>
#include <heap.h>
#include <cpu.h>

static const char *exception_names[] = {
    "Breakpoint",
    "Arithmetic Error",
    "Assertion Failure",
    "Bad Operation",
    "Memory Access Fault",
};

static void raise_exception_internal(thread_t *thread, processor_mode_t mode, exception_info_t *info, registers_t *exception_regs)
{
    if (mode == USER_MODE)
    {
        bool_t current = (thread == get_current_thread());
        thread->user_exception_info = *info;
        registers_t *regs = (current || (thread->in_kernel > 0)) ? thread->last_context : &thread->state.regs;

        if (thread->user_handler.eip)
        {
            *regs = thread->user_handler;
            regs->eax = 1;
            regs->error_code = 0;

            ASSERT((regs->cs & 0xFFFC) == 0 || SEGMENT_RPL(regs->cs) == 3);
            ASSERT((regs->data_selector & 0xFFFC) == 0 || SEGMENT_RPL(regs->data_selector) == 3);

            if (current || (thread->in_kernel > 0))
            {
                registers_ext_t *regs_ext = (registers_ext_t*)regs;
                regs_ext->esp3 = regs->esp;
            }
        }
        else
        {

            dword_t exit_code = 1; // TODO: Perhaps something more meaningful
            process_t *proc = thread->owner_process;
            reference(&proc->header);
            terminate_process(proc, exit_code);
            dereference(&proc->header);
        }
    }
    else
    {
        ASSERT(thread == get_current_thread());
        thread->kernel_exception_info = *info;

        if (thread->kernel_handler.eip)
        {
            thread->kernel_handler.eax = 1;
            memcpy(exception_regs, &thread->kernel_handler, sizeof(registers_t));
        }
        else
        {
            KERNEL_CRASH_WITH_REGS(exception_names[info->number], exception_regs);
        }
    }
}

static void exception_handler(registers_t *regs, byte_t int_num)
{
    exception_info_t info;
    processor_mode_t previous_mode = SEGMENT_RPL(regs->cs) == 0 ? KERNEL_MODE : USER_MODE;
    void *faulting_address;

    info.state = *regs;
    memset(info.parameters, 0, sizeof(info.parameters));

    switch (int_num)
    {
    case CPU_EXCEPTION_DE:
    case CPU_EXCEPTION_MF:
        info.number = EXCEPTION_ARITHMETIC;
        break;

    case CPU_EXCEPTION_DB:
    case CPU_EXCEPTION_BP:
        info.number = EXCEPTION_BREAKPOINT;
        break;

    case CPU_EXCEPTION_NMI:
    case CPU_EXCEPTION_MC:
        return;

    case CPU_EXCEPTION_OF:
    case CPU_EXCEPTION_BR:
    case CPU_EXCEPTION_AC:
        info.number = EXCEPTION_ASSERTION;
        break;

    case CPU_EXCEPTION_NM:
        if (cpu_fpu_present)
        {
            thread_lazy_fpu();
            return;
        }
        else
        {
            info.number = EXCEPTION_BAD_OPERATION;
        }

        break;

    case CPU_EXCEPTION_DF:
        KERNEL_CRASH_WITH_REGS("Double Fault", regs);
        return;

    case CPU_EXCEPTION_GP:
        if (regs->eflags & CPU_STATUS_FLAG_VM)
        {
            vm86_handler((registers_ext_vm86_t*)regs);
            return;
        }

    case CPU_EXCEPTION_UD:
    case CPU_EXCEPTION_TS:
    case CPU_EXCEPTION_NP:
    case CPU_EXCEPTION_SS:
        info.number = EXCEPTION_BAD_OPERATION;
        break;

    case CPU_EXCEPTION_PF:
        faulting_address = (void*)cpu_read_faulting_address();
        if (memory_fault_handler(faulting_address, regs)) return;

        info.number = EXCEPTION_MEMORY_ACCESS;
        memcpy(info.parameters, &faulting_address, sizeof(faulting_address));
        break;

    default:
        KERNEL_CRASH_WITH_REGS("Unexpected CPU exception", regs);
    }

    thread_t *thread = get_current_thread();
    if (thread == NULL) KERNEL_CRASH_WITH_REGS(exception_names[info.number], regs);
    raise_exception_internal(thread, previous_mode, &info, regs);
}

sysret_t syscall_raise_exception(handle_t thread_handle, const exception_info_t *info)
{
    exception_info_t safe_info;

    if (get_previous_mode() == USER_MODE)
    {
        if (!check_usermode(info, sizeof(exception_info_t))) return ERR_BADPTR;

        EH_TRY safe_info = *info;
        EH_CATCH EH_ESCAPE(return ERR_BADPTR);
        EH_DONE;
    }
    else
    {
        safe_info = *info;
    }

    thread_t *thread = NULL;

    if (thread_handle == INVALID_HANDLE)
    {
        thread = get_current_thread();
        reference(&thread->header);
    }
    else
    {
        if (!reference_by_handle(thread_handle, OBJECT_THREAD, (object_t**)&thread)) return ERR_INVALID;
    }

    raise_exception_internal(thread, USER_MODE, &safe_info, NULL);

    dereference(&thread->header);
    return ERR_SUCCESS;
}

sysret_t syscall_get_exception_info(exception_info_t *info)
{
    thread_t *thread = get_current_thread();

    if (get_previous_mode() == USER_MODE)
    {
        if (!check_usermode(info, sizeof(exception_info_t))) return ERR_BADPTR;

        EH_TRY memcpy(info, &thread->user_exception_info, sizeof(exception_info_t));
        EH_CATCH EH_ESCAPE(return ERR_BADPTR);
        EH_DONE;
    }
    else
    {
        *info = thread->kernel_exception_info;
    }

    return ERR_SUCCESS;
}

void set_exception_handler(registers_t *regs, processor_mode_t mode, exception_handler_t *old_handler)
{
    thread_t *thread = get_current_thread();

    if (mode == KERNEL_MODE)
    {
        *old_handler = thread->kernel_handler;
        thread->kernel_handler = *regs;
    }
    else
    {
        if (!check_usermode(old_handler, sizeof(exception_handler_t))) return;

        EH_TRY
        {
            *old_handler = thread->user_handler;
            thread->user_handler = *regs;
        }
        EH_DONE;
    }
}

sysret_t syscall_save_exception_handler(exception_handler_t *old_handler)
{
    set_exception_handler(old_handler, USER_MODE, get_current_thread()->last_context);
    return 0;
}

sysret_t syscall_restore_exception_handler(const exception_handler_t *old_handler)
{
    thread_t *thread = get_current_thread();

    if (get_previous_mode() == USER_MODE)
    {
        exception_handler_t safe_handler;
        if (!check_usermode(old_handler, sizeof(exception_handler_t))) return ERR_BADPTR;

        EH_TRY
        {
            safe_handler = *old_handler;
        }
        EH_CATCH
        {
            EH_ESCAPE(return ERR_BADPTR);
        }
        EH_DONE;

        if (((safe_handler.cs & 0xFFFC) != 0 && SEGMENT_RPL(safe_handler.cs) != 3)
            || ((safe_handler.data_selector & 0xFFFC) != 0
            && SEGMENT_RPL(safe_handler.data_selector) != 3))
        {
            return ERR_INVALID;
        }

        thread->user_handler = safe_handler;
    }
    else
    {
        thread->kernel_handler = *old_handler;
    }

    return ERR_SUCCESS;
}

void exceptions_init()
{
    byte_t i;
    for (i = 0; i < CPU_EXCEPTION_MAX; i++) set_int_handler(i, exception_handler, FALSE, FALSE);
}
